package com.sl.au.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.ContractInfo;
import com.sl.au.entity.ExdeTbOPPlanTask;
import com.sl.au.entity.ExdeTbOPPlanTaskDetail;
import com.sl.au.entity.ExdeTbOPPlanTaskDetailReplace;
import com.sl.au.entity.Module;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.ContractService;
import com.sl.au.service.ExdeSchedulingService;

@RestController
@RequestMapping(value = "/ui/scheduling/")
public class ExdeSchedulingController extends BaseController {

	@Autowired
	ExdeSchedulingService exdeSchedulingService;
	
	@Autowired
	AttachmentService attachmentService;
	
	@Autowired
	ContractService contractService;
	
	
	/**
	 * 合同管理页面显示
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		Module module = this.getPageModule("ExdeTbOPPlanTask");
		ModelAndView modelAndView = this.createLayoutView("scheduling/schedulingindex");
		Account a = this.getMyAccount();
		User user = a.getUser();
		modelAndView.addObject("user", user);
		modelAndView.addObject("module", module);
		
		return modelAndView;
	}
	
	/**
	 * 获取页面数据
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String state = request.getParameter("state");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String areaName = a.getUser().getSaleArea().getAreaName();
		String name = "schedulingindex";
		Module module = this.getPageModule(name);
		String dataFilter = module.getDataFilter();
		//String dataFilter = "所有";
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		if (userId == null) {
			userId = "";
		}
		if (superior == null) {
			superior = "";
		}
		if (areaName == null) {
			areaName = "";
		}
		if (dataFilter == null) {
			dataFilter = "";
		}
		condition.put("key", key);
		condition.put("state", state);
		condition.put("userId", userId);
		condition.put("superior", superior);
		condition.put("areaName", areaName);
		condition.put("dataFilter", dataFilter);
		List<ExdeTbOPPlanTask> exdeTbOPPlanTasks = exdeSchedulingService.getContractInfos(start, length, condition, null, null);
		long count = exdeSchedulingService.getContractInfosCount(condition);
		map.put("data", exdeTbOPPlanTasks);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 生成计划任务
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "generationplan", method = RequestMethod.GET)
	public long GenerationPlan(HttpServletRequest request) {
		String contractInfo = request.getParameter("contractInfo");
		int result = 0;
		if (StringUtils.hasText(contractInfo)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			// params[0]是contractId数据; params[1]是contractType数据
			String[] params = contractInfo.split(":");
			if (params.length == 2){
				String[] ids = params[0].split(",");
				result = exdeSchedulingService.saveExdeTbOPPlanTask(ids, user);
				
			}
		}
		return result;
	}
	
	/**
	 * 修改计划任务
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "UpdatePlan", method = RequestMethod.GET)
	public long UpdatePlan(HttpServletRequest request) {
		String schedulingIds = request.getParameter("schedulingIds");
		int result = 0;
		if (StringUtils.hasText(schedulingIds)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			// params[0]是contractId数据; params[1]是contractType数据
			//String[] params = schedulingIds.split(":");
			//if (params.length == 2){
			String[] ids = schedulingIds.split(",");
			result = exdeSchedulingService.updateExdeTbOPPlanTask(ids, user);
			//}
		}
		return result;
	}
	
	/**
	 * 获取泵信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getPlanTaskDetail", method = RequestMethod.GET)
	public Map<String, Object> getPlanTaskDetail(HttpServletRequest request) {
		String id = request.getParameter("id");
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		Map<String, Object> map = new HashMap<String, Object>();
		List<ExdeTbOPPlanTaskDetail> exdeTbOPPlanTaskDetails = new ArrayList<ExdeTbOPPlanTaskDetail>();
		long count = 0;
		if (StringUtils.hasText(id)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			exdeTbOPPlanTaskDetails = exdeSchedulingService.getPlanTaskDetail(start, length, id, null, null);
			count = exdeSchedulingService.getPlanTaskDetailCount(0, Integer.MAX_VALUE, id, null, null);
		}
		map.put("data", exdeTbOPPlanTaskDetails);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 编辑计划任务
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getPlanTaskDetailReplace", method = RequestMethod.GET)
	public Map<String, Object> getPlanTaskDetailReplace(HttpServletRequest request) {
		String id = request.getParameter("id");
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		Map<String, Object> map = new HashMap<String, Object>();
		List<ExdeTbOPPlanTaskDetailReplace> exdeTbOPPlanTaskDetailReplaces = new ArrayList<ExdeTbOPPlanTaskDetailReplace>();
		long count = 0;
		if (StringUtils.hasText(id)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			exdeTbOPPlanTaskDetailReplaces = exdeSchedulingService.getPlanTaskDetailReplace(start, length, id, null, null);
			count = exdeSchedulingService.getPlanTaskDetailReplaceCount(0, Integer.MAX_VALUE, id, null, null);
		}
		map.put("data", exdeTbOPPlanTaskDetailReplaces);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 打印
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "printscheduling", method = RequestMethod.GET)
	public ResponseEntity<Resource> printScheduling(HttpServletRequest request) throws IOException {
		String id = request.getParameter("id");
		Account account = this.getMyAccount();
		String sender = account.getLoginInfo().getName();
		String filename = exdeSchedulingService.genQuoteDocx(id, sender);
		Resource file = null;
		String shortName = "订货合同计划任务单.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}
	/**
	 * 打印备件计划任务
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "printBJScheduling", method = RequestMethod.GET)
	public ResponseEntity<Resource> printBJScheduling(HttpServletRequest request) throws IOException {
		String id = request.getParameter("id");
		Account account = this.getMyAccount();
		User user = account.getUser();
		//String sender = account.getLoginInfo().getName();
		String filename = exdeSchedulingService.genBJScheduling(id, user);
		Resource file = null;
		String shortName = "备件合同排产、装箱机发运单.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}
	/**
	 * 保存计划任务
	 * @param request
	 * @param exdeTbOPPlanTask
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "savePlanTask/{id}", method = RequestMethod.POST)
	public int savePlanTask( HttpServletRequest request,@RequestBody ExdeTbOPPlanTask exdeTbOPPlanTask, @PathVariable String id) {
		ExdeTbOPPlanTask old = exdeSchedulingService.getExdeSchedulingRepository().findOne(id);
		if(exdeTbOPPlanTask!=null){
			exdeTbOPPlanTask.setcAcceptPersonName(old.getcAcceptPersonName());
			exdeTbOPPlanTask.setnAcceptPersonId(old.getnAcceptPersonId());
			exdeTbOPPlanTask.setdAcceptDate(old.getdAcceptDate());
			exdeTbOPPlanTask.setcIsGenerated(old.getcIsGenerated());
			exdeTbOPPlanTask.setUser(old.getUser());
			exdeTbOPPlanTask.setcCreateDept(old.getcCreateDept());
			exdeTbOPPlanTask.setAreaName(old.getAreaName());
			exdeTbOPPlanTask.setcState(old.getcState());
			exdeTbOPPlanTask.setnUserUnitId(old.getnUserUnitId());
			exdeTbOPPlanTask.setdIssuedDate(old.getdIssuedDate());
			exdeTbOPPlanTask.setContractInfo(old.getContractInfo());
			exdeTbOPPlanTask.setContractType(old.getContractType());
			exdeTbOPPlanTask.setnPrintCount(old.getnPrintCount());
			exdeTbOPPlanTask.setnPrintDate(old.getnPrintDate());
			exdeTbOPPlanTask.setcType(old.getcType());
			exdeSchedulingService.getExdeSchedulingRepository().save(exdeTbOPPlanTask);
			return 1;
		}
		return 0;
	}
	/**
	 * 下达计划任务
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "issuedplan", method = RequestMethod.POST)
	public int issuedplan( HttpServletRequest request) {
		String schedulingIds = request.getParameter("schedulingIds");
		int result = 0;
		if (StringUtils.hasText(schedulingIds)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			// params[0]是contractId数据; params[1]是contractType数据
			String[] ids = schedulingIds.split(",");
			if (ids.length > 0){
				result = exdeSchedulingService.issuedplan(ids, user);
				
			}
		}
		return result;
	}
	/**
	 * 收回计划任务
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "regainPlanTask", method = RequestMethod.GET)
	public int regainPlanTask( HttpServletRequest request) {
		String schedulingIds = request.getParameter("schedulingIds");
		int result = 0;
		if (StringUtils.hasText(schedulingIds)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			// params[0]是contractId数据; params[1]是contractType数据
			String[] ids = schedulingIds.split(",");
			if (ids.length > 0){
				result = exdeSchedulingService.regainPlanTask(ids, user);
			}
		}
		return result;
	}
	@RequestMapping(value = "deletePlanTask", method = RequestMethod.DELETE)
	public int deletePlanTask( HttpServletRequest request) {
		String schedulingIds = request.getParameter("schedulingIds");
		int result = 0;
		if (StringUtils.hasText(schedulingIds)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			// params[0]是contractId数据; params[1]是contractType数据
			String[] ids = schedulingIds.split(",");
			if (ids.length > 0){
				result = exdeSchedulingService.deletePlanTask(ids, user);
			}
		}
		return result;
	}
	
	@RequestMapping(value = "schedulingEdit/{id}/{type}")
	public ModelAndView schedulingEdit(@PathVariable String id, @PathVariable String type) {
		ModelAndView modelAndView = null;
		if(type.equals("up"))
			modelAndView = this.createLayoutView("scheduling/schedulingedit");
		else
			modelAndView = this.createLayoutView("scheduling/schedulingsee");
			
		if(id!=null&&!id.equals("")){
			ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingService.getExdeSchedulingRepository().findOne(id);
			System.out.println(exdeTbOPPlanTask.getdInterfaceDate());
			//exdeTbOPPlanTask.setdInterfaceDate(null);
			modelAndView.addObject("exdeTbOPPlanTask", exdeTbOPPlanTask);
		}
		return modelAndView;
	}
}
